package com.itheima.fiilter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;


@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain Chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 设置CORS响应头
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "token, Content-Type, Authorization, X-Requested-With");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        System.out.println("LoginCheckFilter拦截");
        String url = request.getRequestURI();
        //放行登录注册请求
        if (url.contains("account") ) {
            Chain.doFilter(request, response);
            return;
        }
        System.out.println("Accept:"+ request.getHeader("Accept"));
        System.out.println("token:" + request.getHeader("token"));
        String jwt= request.getHeader("token");
        System.out.println( "jwt:"+jwt);
        if (jwt==null || jwt.isEmpty()) {
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        try {
            JwtUtils.parseJWT(jwt);
            Chain.doFilter(request, response);
        } catch (Exception ignored) {
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

    }
}
